import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import {
  Card,
  Table,
  Switch,
  Drawer,
  Form,
  Button,
  Input,
  Space,
  Select,
  Typography,
  Row,
  Col,
  Upload,
  Tooltip,
  message,
  Modal,
  Image,
} from 'antd';
import { connect } from 'umi';
import IconFont from '@/components/Iconfont';
import UploadUtil from '@/components/UploadUtil';
import { ExclamationCircleOutlined, LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import imgAvatar from '@/assets/Picture.png';

const { Paragraph } = Typography;
const { Option } = Select;
const { confirm } = Modal;

const selectAfter = (
  <Select defaultValue="@163.com" className="select-after">
    <Option value="@163.com">@163.com</Option>
    <Option value="@126.com">@126.com</Option>
    <Option value="@qq.com">@qq.com</Option>
    <Option value="@gmail.com">@gmail.com</Option>
    <Option value="@outlook.com">@outlook.com</Option>
  </Select>
);
class ViewPage extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      loadingSave: false,
      disabled: true,
      dataSource: [],
      imageUrl: null,
      imgList1: [],
      visible: false,
      record: {},
      selectedRowKeys: [],
    };
  }
  formRef: any = React.createRef();
  componentDidMount() {
    this.fetchData();
  }
  fetchData = () => {
    this.setState({ loading: true });
    this.props
      .dispatch({
        type: 'Abp/getAll',
        payload: { SkipCount: 0, MaxResultCount: 100 },
        control: 'Customers',
      })
      .then(() => {
        var resp = this.props.response.result?.items;
        this.setState({
          selectedRowKeys: [],
          dataSource: resp,
          loading: false,
        });
      });
  };
  showDrawer = (record?: any) => {
    this.setState({ visible: true, record });
    setTimeout(() => {
      if (record) {
        this.formRef.current.setFieldsValue({ model: record });
        if (record.businessLicense)
          this.setState({ imageUrl: UploadUtil.getOssFile + record.businessLicense });
      }
      this.setState({ disabled: false });
    }, 1000);
  };

  onClose = () => {
    this.setState({ visible: false, loading: false, disabled: true, imageUrl: null });
  };
  onFinish = async (values: any) => {
    this.setState({ loadingSave: true });
    var act = 'Abp/update';
    if (values.model.id == 0 || !values.model.id) {
      act = 'Abp/create';
    }
    if (this.state.imgList1 && this.state.imgList1.length > 0) {
      var pic = await UploadUtil.uploadPic(
        this.state.imgList1,
        values.model.id,
        'Customers',
        'BusinessLicense',
      );
      values.model.businessLicense = pic;
    }
    this.props
      .dispatch({
        type: act,
        payload: values.model,
        control: 'Customers',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('保存成功！');
          this.fetchData();
        } else {
          message.error('保存错误，请联系管理员！');
        }
        this.setState({ loadingSave: false });
      });
  };
  onSelectChange = (selectedRowKeys: any) => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
  confirmDel = (id: number) => {
    let _this = this;
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: '确定删除此客户？此操作将不可挽回！',
      onOk() {
        _this.onDelete(id);
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  onDelete = (id: number) => {
    this.setState({ loading2: true });
    this.props
      .dispatch({
        type: 'Abp/delete',
        payload: { id },
        control: 'Customers',
      })
      .then(() => {
        var resp = this.props.response;
        if (resp.success) {
          message.success('删除成功！');
          this.fetchData();
        }
        this.setState({ loading2: false });
      });
  };
  handleChange = (info: any) => {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      UploadUtil.getBase64(info.file.originFileObj, (imageUrl: any) =>
        this.setState({
          imageUrl,
          imgList1: info.fileList,
        }),
      );
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  };
  render() {
    const { selectedRowKeys, record, loading, imageUrl } = this.state;
    const columns = [
      {
        title: '客户名称',
        dataIndex: 'customerName',
        key: 'CustomerName',
      },
      {
        title: '商户号(AppID)',
        dataIndex: 'appID',
        key: 'appID',
        render: (text: string) => <Paragraph copyable>{text}</Paragraph>,
      },
      {
        title: '状态',
        dataIndex: 'isActive',
        key: 'isActive',
        render: (text: boolean | undefined) => (
          <span>
            <Switch defaultChecked={text} />
          </span>
        ),
      },
      {
        render: (record: any) => (
          <span>
            <a onClick={() => this.showDrawer(record)}>配置</a>
          </span>
        ),
      },
    ];
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const uploadButton = (
      <div>
        {loading ? <LoadingOutlined /> : <PlusOutlined />}
        <div className="ant-upload-text">Upload</div>
      </div>
    );
    return (
      <PageHeaderWrapper title={false} breadcrumbRender={false} ghost>
        <Row gutter={[16, 16]}>
          <Col span={24}>
            <Card>
              <Space>
                <Button type="primary" onClick={this.fetchData} loading={this.state.loading}>
                  刷新
                </Button>
                <Button type="dashed" onClick={() => this.showDrawer(null)} icon={<PlusOutlined />}>
                  新建客户
                </Button>
              </Space>
            </Card>
          </Col>
          <Col span={24}>
            <Table
              rowKey="id"
              rowSelection={rowSelection}
              dataSource={this.state.dataSource}
              columns={columns}
            />
          </Col>
        </Row>
        <Drawer
          title={record?.CustomerName}
          placement="right"
          closable={false}
          visible={this.state.visible}
          destroyOnClose={true}
          width={600}
        >
          <Form layout="vertical" ref={this.formRef} onFinish={this.onFinish}>
            <Form.Item
              label="客户名称"
              name={['model', 'customerName']}
              rules={[{ required: true, message: '客户名称必填' }]}
            >
              <Input placeholder="请输入客户名称" />
            </Form.Item>
            <Form.Item style={{ marginBottom: 0 }}>
              <Input.Group compact>
                <Form.Item
                  label={
                    <Tooltip title="商户号是商户进行接口调用的唯一标识，客户手动更新商户号，商户号只允许一个月更新一次">
                      {' '}
                      商户号 <IconFont type="icon-wenhao" />
                    </Tooltip>
                  }
                  name={['model', 'appID']}
                >
                  <Input disabled placeholder="请输入商户号" />
                </Form.Item>
                <Form.Item
                  label={
                    <Tooltip title="商户调用接口获取AppId时所需要的密码">
                      {' '}
                      独立密码 <IconFont type="icon-wenhao" />
                    </Tooltip>
                  }
                  name={['model', 'password']}
                  rules={[{ required: true, message: '独立密码必填' }]}
                >
                  <Input.Password placeholder="请输入独立密码" />
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item
              label="注册地址"
              name={['model', 'regAddress']}
              rules={[{ required: true, message: '注册地址必填' }]}
            >
              <Input placeholder="请输入注册地址" />
            </Form.Item>
            <Form.Item
              label="联系地址"
              name={['model', 'contAddress']}
              rules={[{ required: true, message: '联系地址必填' }]}
            >
              <Input placeholder="请输入联系地址，详细到街道、门牌号" />
            </Form.Item>

            <Form.Item style={{ marginBottom: '0px' }}>
              <Input.Group compact>
                <Form.Item label="行业" name={['model', 'industry']}>
                  <Select style={{ width: 200 }} placeholder="请选择行业">
                    <Select.Option value="jack">制造业</Select.Option>
                    <Select.Option value="lucy">金融</Select.Option>
                    <Select.Option value="Yiminghe">农业</Select.Option>
                    <Select.Option value="IT">计算机</Select.Option>
                  </Select>
                </Form.Item>
                <Form.Item label="行业分支" name={['model', 'industryDtl']}>
                  <Select style={{ width: 200 }} placeholder="请选择行业分支">
                    <Select.Option value="jack">电子商务</Select.Option>
                    <Select.Option value="lucy">软件开发</Select.Option>
                  </Select>
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item style={{ marginBottom: '0px' }}>
              <Input.Group compact>
                <Form.Item
                  label="营业执照副本"
                  name={['model', 'businessLicense']}
                  style={{ width: 160 }}
                >
                  <Upload
                    name="avatar"
                    listType="picture-card"
                    className="avatar-uploader"
                    showUploadList={false}
                    beforeUpload={UploadUtil.beforeUpload}
                    onChange={this.handleChange}
                  >
                    {imageUrl ? (
                      <img src={imageUrl} alt="avatar" style={{ width: '100%' }} />
                    ) : (
                      uploadButton
                    )}
                  </Upload>
                </Form.Item>
              </Input.Group>
            </Form.Item>
            <Form.Item style={{ marginBottom: '0px' }}>
              <Input.Group compact>
                <Form.Item
                  label="联系人"
                  name={['model', 'contactor']}
                  rules={[{ required: true, message: '联系人必填' }]}
                >
                  <Input placeholder="联系人" />
                </Form.Item>
                <Form.Item
                  label="联系电话"
                  name={['model', 'telphone']}
                  rules={[{ required: true, message: '联系电话必填' }]}
                >
                  <Input placeholder="联系电话" />
                </Form.Item>
                <Form.Item
                  label="电子邮箱"
                  name={['model', 'email']}
                  rules={[{ required: true, message: '联系电话必填' }]}
                >
                  <Input placeholder="电子邮箱" />
                </Form.Item>
                <Form.Item label="是否启用" name={['model', 'isActive']} valuePropName="checked">
                  <Switch />
                </Form.Item>
              </Input.Group>
            </Form.Item>

            <Form.Item name={['model', 'id']} style={{ display: 'none' }}>
              <Input />
            </Form.Item>
            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={this.state.loadingSave}
                  disabled={this.state.disabled}
                >
                  保存
                </Button>
                <Button onClick={this.onClose}>取消</Button>
                <Button
                  style={{ marginLeft: 260 }}
                  type="primary"
                  danger
                  onClick={() => this.confirmDel(this.state.record?.id)}
                  disabled={this.state.disabled}
                >
                  删除
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Drawer>
      </PageHeaderWrapper>
    );
  }
}
export default connect(({ Abp, Department }: API.IConnectState) => ({
  response: Abp.response,
  currentUser: Abp.currentUser,
  departments: Department.departments,
}))(ViewPage);
